package model

import (
	"github.com/jmoiron/sqlx"
	"time"
	"zimuzu_cvn_web_api/config"
	. "zimuzu_cvn_web_api/pkg/e"
	"zimuzu_cvn_web_api/pkg/errno"
)

type UserWalletAddressDb struct {
	Id          int64  `db:"id" json:"id"`
	Uid         int64  `db:"uid" json:"uid"`
	CoinType    string `db:"coin_type" json:"coin_type"`
	Address     string `db:"address" json:"address"`
	Status      int64  `db:"status" json:"status"`
	CreateTime  int64  `db:"create_time" json:"create_time"`
	UpdateTime  int64  `db:"update_time" json:"update_time"`
	SignString  string `db:"sign_string" json:"sign_string"`
	SignVersion string `db:"sign_version" json:"sign_version"`
}

//检查用户钱包地址是否存在
//Auth: TXG
func ExistUserWalletAddress(uid int64) (ok bool, err error) {
	var qi int
	coinType := COIN_TYPE_ERC20
	err = sqlx.Get(config.C.DB.DB, &qi, "SELECT count(*) FROM user_wallet_address WHERE uid = ? and coin_type = ? and status = 1", uid, coinType)
	if err != nil {
		Log("err", err)
		return false, err
	}
	if qi == 0 {
		return false, nil
	} else if qi != 1 {
		Log("err", errno.DbDataError)
		return false, err
	}
	return true, nil
}

//添加钱包地址
//Auth: TXG
func AddUserWalletAddress(qi *UserWalletAddressDb) (err error) {
	qi.Status = 1
	qi.CreateTime = time.Now().Unix()
	qi.UpdateTime = time.Now().Unix()
	_, err = sqlx.NamedExec(config.C.DB.DB, `insert into user_wallet_address (uid,coin_type,address,status,create_time,update_time,sign_string,sign_version) values (:uid,:coin_type,:address,:status,:create_time,:update_time,:sign_string,:sign_version)`, *qi)
	if err != nil {
		Log("err", err)
	}
	return err
}

//获取钱包地址（uid）
//Auth: TXG
func GetUserWalletAddress(uid int64) (qi UserWalletAddressDb, err error) {
	coinType := COIN_TYPE_ERC20
	err = sqlx.Get(config.C.DB.DB, &qi, "select id,uid,coin_type,address,status,create_time,update_time,sign_string,sign_version from user_wallet_address where uid = ? and coin_type = ? and status = 1", uid, coinType)
	if err != nil {
		Log("err", err)
	}
	return qi, err
}

//获取钱包地址（address）
//Auth: TXG
func GetUserWalletAddressByAddress(address string) (qi UserWalletAddressDb, err error) {
	err = sqlx.Get(config.C.DB.DB, &qi, "select id,uid,coin_type,address,status,create_time,update_time,sign_string,sign_version from user_wallet_address where address = ?", address)
	if err != nil {
		Log("err", err)
	}
	return qi, err
}